import express from 'express';
import CryptoJS from 'crypto-js';
import crypto from 'crypto';
import { Base64 } from 'js-base64'
import CONFIG from '../../../config/config.config'
import wechatApi from '../../lib/wechatapi'; // 微信接口API
import { User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt } from '../../utils/utils'; // 工具类

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // User.Modal.sync();
  // 权限校验
  // await checkPermission(Request, Response, minLevel)

  let param = Request.body
  let appId = CONFIG.appid

  let sessionKey = ''
  let openId = ''
  await getSessionKey(param.code, Response).then(res => {
    sessionKey = new Buffer(res.session_key, 'base64')
    openId = res.openid
  });

  // base64 decode
  let encryptedData = new Buffer(param.encryptedData, 'base64')
  let iv = new Buffer(param.iv, 'base64')

  // 解密
  let decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
  // 设置自动 padding 为 true，删除填充补位
  decipher.setAutoPadding(true)
  let decoded = decipher.update(encryptedData, 'binary', 'utf8')
  decoded += decipher.final('utf8')
  decoded = JSON.parse(decoded) // 解密出来的用户数据
  if (!decoded.openId) {
    // Response.status(300).send({ message: "抱歉，用户登陆信息获取失败" });
    decoded.openId = openId
  }

  User.Modal.upsert(decoded).then(async res => {
    await getUserIdByOpenId(openId).then(res => {
      // 构造token并存储
      let tokenOrigin = `{"uid":"${res.id}","timeStamp":"${new Date().valueOf()}"}`
      Response.append('token', aesEncrypt(tokenOrigin));
      // Response.cookie("token", tokenOrigin, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true, signed: true });
    });
    // res为true则新增，false则更新
    let msg = '登陆成功'
    if (res === true) {
      msg = '一键注册成功'
    }
    Response.json({
      data: msg
    })
  }).catch(err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function getSessionKey(code, Response) {
  // 通过code获取sessionKey
  return new Promise((resolve, reject) => {
    wechatApi.codeToSession({ js_code: code, grant_type: 'authorization_code' }).then(res => {
      if (res.errcode && res.errmsg) {
        Response.status(300).send({ message: res.errmsg });
      } else {
        resolve(res) // session_key, openid
      }
    })
  })
}

function getUserIdByOpenId(openId, Response) {
  // 通过openId获取用户id
  return new Promise((resolve, reject) => {
    User.Modal.findAll({
      where: {
        openId: openId,
      },
      raw: true,
    }).then(res => {
      if (res && res.length > 0) {
        resolve(res[0])
      } else {
        Response.status(300).send({ message: "查询用户失败，请提供正确openId" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;